﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.IO;
using JSLCloud.Models;
using Microsoft.AspNetCore.Authorization;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Drawing.Drawing2D;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace JSLCloud.App.Mes.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly AppConfig _appConfig;
        private readonly IDbContext _db;//数据库操作实例对象

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="option"></param>
        /// <param name="dbContext"></param>
        public FilesController(IOptions<AppConfig> option, IDbContext dbContext)
        {
            _appConfig = option.Value;
            _db = dbContext;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">需要上传的文件,只能上传单个文件</param>
        /// <returns></returns>
        [HttpOptions("Upload")]
        [HttpPost("Upload")]
        [AllowAnonymous]
        public IActionResult Post(IFormFile file)
        {
            if (string.IsNullOrEmpty(_appConfig.FileUploadDirectory))
                return new NoContentResult();
            if (file == null&&( Request.Form.Files==null|| Request.Form.Files.Count==0))
                return new NotFoundResult();

            var fileAim = file == null ? Request.Form.Files[0] : file;
            try
            {
                var fileDir = $"{_appConfig.FileUploadDirectory}/{DateTime.Now.ToString("yyyyMMdd")}";
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                //文件名称
                var currFileName = fileAim.FileName;
                var fileSuffix = currFileName.Substring(currFileName.LastIndexOf("."));
                var newFileName = GetNewFileName();
                currFileName = newFileName + fileSuffix;
                //上传的文件的路径
                var filePath = $"{fileDir}/{currFileName}";
                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    fileAim.CopyTo(fs);
                    fs.Flush();
                }
                return new OkObjectResult($"{DateTime.Now.ToString("yyyyMMdd")}/{currFileName}");
            }
            catch
            {
                return new NotFoundResult();
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">需要上传的文件,只能上传单个文件</param>
        /// <returns></returns>
        [HttpOptions("FileUpload")]
        [HttpPost("FileUpload")]
        [AllowAnonymous]
        public IActionResult FileUpload(IFormFile file)
        {
            if (string.IsNullOrEmpty(_appConfig.FileUploadDirectory))
                return new NoContentResult();
            if (file == null && (Request.Form.Files == null || Request.Form.Files.Count == 0))
                return new NotFoundResult();


            var fileAim = file ?? Request.Form.Files[0];
            try
            {
                var fileDir = $"{_appConfig.FileUploadDirectory}/{DateTime.Now.ToString("yyyyMMdd")}";
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                //文件名称
                var currFileName = fileAim.FileName;
                var fileSuffix = currFileName.Substring(currFileName.LastIndexOf(".")+1);
                var newFileName = GetNewFileName();
                currFileName = newFileName + fileSuffix;
                //上传的文件的路径
                var filePath = $"{fileDir}/{currFileName}";
                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    fileAim.CopyTo(fs);
                    fs.Flush();
                }

                var returnFilePath = $"{DateTime.Now.ToString("yyyyMMdd")}/{currFileName}";
                var userid = TokenManager.GetCurentUserbyToken(Request.Headers).UserID;


                return new OkObjectResult($"{returnFilePath}");
            }
            catch(Exception ex)
            {
                return new NotFoundResult();
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">需要上传的文件,只能上传单个文件</param>
        /// <returns></returns>
        [HttpOptions]
        [HttpPost]
        [AllowAnonymous]
        [Route("[action]")]
        public IActionResult FilesUpload(IFormFile file)
        {
            if (string.IsNullOrEmpty(_appConfig.FileUploadDirectory))
                return new NoContentResult();
            if (file == null && (Request.Form.Files == null || Request.Form.Files.Count == 0))
                return new NotFoundResult();


            var fileAim = file ?? Request.Form.Files[0];
            if (fileAim.Length / 1024 /1024 >= 10)
                return new NotFoundResult();
            try
            {
                var fileDir = $"{_appConfig.FileUploadDirectory}/{DateTime.Now.ToString("yyyyMMdd")}";
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                //文件名称
                var currFileName = fileAim.FileName;
                var fileSuffix = currFileName.Substring(currFileName.LastIndexOf("."));
                var newFileName = GetNewFileName();
                currFileName = newFileName + fileSuffix;
                //上传的文件的路径
                var filePath = $"{fileDir}/{currFileName}";
                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    fileAim.CopyTo(fs);
                    fs.Flush();
                }

                var returnFilePath = $"{DateTime.Now.ToString("yyyyMMdd")}/{currFileName}";
                //文件上传成功插入上传记录
                var fileModel = new
                {
                    Wjdx = fileAim.Length / 1024, //单位KB
                    Wjlj = returnFilePath,
                    Wjlx = fileSuffix,
                    Wjmc = fileAim.FileName.Substring(0, fileAim.FileName.LastIndexOf("."))
                };


                return new OkObjectResult($"{JsonConvert.SerializeObject(fileModel)}");
            }
            catch
            {
                return new NotFoundResult();
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">需要上传的文件,只能上传单个文件</param>
        /// <returns></returns>
        [HttpOptions("FileUploads")]
        [HttpPost("FileUploads")]
        [AllowAnonymous]
        public async Task<IActionResult> FileUploads()
        {
            if (string.IsNullOrEmpty(_appConfig.FileUploadDirectory))
                return new NoContentResult();

            if (Request.Form.Files == null || Request.Form.Files.Count == 0)
                return new NotFoundResult();

            var result = new List<dynamic>();
            foreach (var file in Request.Form.Files)
            {
                var fileAim = file;
                try
                {
                    var fileDir = $"{_appConfig.FileUploadDirectory}/{DateTime.Now.ToString("yyyyMMdd")}";
                    if (!Directory.Exists(fileDir))
                    {
                        Directory.CreateDirectory(fileDir);
                    }
                    //文件名称
                    var currFileName = fileAim.FileName;
                    var fileSuffix = currFileName.Substring(currFileName.LastIndexOf("."));
                    var newFileName = GetNewFileName();
                    currFileName = newFileName + fileSuffix;
                    //上传的文件的路径
                    var filePath = $"{fileDir}/{currFileName}";
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        fileAim.CopyTo(fs);
                        fs.Flush();
                    }
                    var returnFilePath = $"{DateTime.Now.ToString("yyyyMMdd")}/{currFileName}";

                    var fileModel = new XmwjwjmxDbModel
                    {
                        Wjdx = (int)(fileAim.Length / 1024), //单位KB
                        Wjlj = returnFilePath,
                        Wjlx = fileSuffix,
                        Wjmc = fileAim.FileName.Substring(0, fileAim.FileName.LastIndexOf("."))
                    };
                    
                    result.Add(fileModel);
                }
                catch
                {
                    return new NotFoundResult();
                }

                await _db.Instance.Insertable(result).ExecuteCommandAsync();
            }
            return new OkObjectResult($"{JsonConvert.SerializeObject(result)}");
        }

        /// <summary>
        /// 删除不需要上传的文件
        /// </summary>
        /// <param name="strFileName">需要删除的文件名称,需要带后缀</param>
        /// <returns></returns>
        [HttpDelete("Delete")]
        [AllowAnonymous]
        public IActionResult Delete(string strFileName)
        {
            if (string.IsNullOrEmpty(_appConfig.FileUploadDirectory))
                return new NoContentResult();
            if (string.IsNullOrEmpty(strFileName))
                return new NotFoundResult();
            try
            {
                var filePath = $"{_appConfig.FileUploadDirectory}/{strFileName}";
                if (!System.IO.File.Exists(filePath))
                {
                    return new OkObjectResult("文件不存在，无需删除");
                }
                else
                {
                    System.IO.File.Delete(filePath);
                    return new OkObjectResult("删除文件成功!");
                }
            }
            catch
            {
                return new NotFoundResult();
            }
        }

        private string GetNewFileName()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }
    }
}
